﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Code {
    public class FileHelper : IFileHelper {
        public IFileProvider FileProvider { get; private set; }

        public readonly IHostingEnvironment _hostingEnvironment;

        public FileHelper() {

        }

        public FileHelper(IHostingEnvironment hostingEnvironment) {
            _hostingEnvironment = hostingEnvironment;
        }

        public async Task<string> ReadTextAsync(string path) {
            byte[] buffer;

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                string content = "";

                fs.Seek(0, SeekOrigin.Begin);

                buffer = new byte[fs.Length];

                int x = await fs.ReadAsync(buffer, 0, buffer.Length);

                if (x > 0) {
                    content = Encoding.Default.GetString(buffer).Replace("\n", "").Replace("\t", "").Replace("\r", ""); ;
                }

                return content;
            }
        }

        public async Task FileSave(IFormFile file, string fileName) {
            var filePath = $"{Directory.GetCurrentDirectory()}/wwwroot/Uploads/{fileName}";

            using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) {
                await file.CopyToAsync(fs);
            }
        }
    }

    public interface IFileHelper {
        Task<string> ReadTextAsync(string path);
    }
}
